package com.example.interceptor;

import com.example.utils.*;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 令牌校验拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("token");

        //2.判断token为空,返回错误信息
        if (token == null || token.isEmpty()) {
            log.info("令牌为空, 响应401");
            response.setStatus(401);
            response.getWriter().write("token is null");
            return false;
        }

        //3.判断token是否合法
        try {
            //令牌解析
            Claims claims = JwtUtils.parseJwt(token);
            //获取员工id,并存到当前线程中
            CurrentHolder.setCurrentId(Integer.valueOf(claims.get("id").toString()));
        } catch (Exception e) {
            log.info("令牌非法, 响应401");
            response.setStatus(401);
            response.getWriter().write("token invalid");
            return false;
        }

        //4.令牌校验通过, 放行
        log.info("令牌合法, 放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理当前线程中的数据");
        CurrentHolder.remove();
    }


}
